package tea_client

import (
	"Student_Mental/DBconfing"
	"Student_Mental/controller/wsService"
	"Student_Mental/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"html"
	"strconv"
)

// ShowClinet
// @Tags 老师端-聊天功能
// @summary 展现聊天窗口列表
// @Router /teacher/client [get]
func ShowClinet(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	Id, _ := c.Cookie("Id")
	rows, _ := sqlDb.Query("SELECT room_id,CASE WHEN uid1 = ? THEN uid1 ELSE uid2 END AS myId,CASE WHEN uid2 = ? THEN uid1 ELSE uid2 END AS toId,student.avatar,student_name FROM room JOIN student ON student.id = CASE WHEN uid2 = ? THEN uid1 ELSE uid2 END WHERE uid1 = ? OR uid2 = ?", Id, Id, Id, Id, Id)
	red, _ := DBconfing.ConnRedis()
	defer red.Close()
	var Rooms []model.Room
	M := wsService.Message{}
	for rows.Next() {
		var s model.Room
		err := rows.Scan(&s.Id, &s.Uid1, &s.Uid2, &s.Avatar, &s.Name)
		if err != nil {
			println(err)
			return
		}
		firstElement, _ := red.LIndex(strconv.Itoa(s.Id), 0).Result()
		if firstElement != "" {
			json.Unmarshal([]byte(firstElement), &M)
			if M.Type == "pic" {
				firstElement = "[图片]"
			} else {
				firstElement = M.Content
			}
		}
		data := model.Room{}
		//Uid1是自己的id，Uid2是另一个id
		// 解码HTML标记
		decodedStr := html.UnescapeString(firstElement)
		data = model.Room{
			Id:         s.Id,
			Uid1:       s.Uid1,
			Uid2:       s.Uid2,
			Avatar:     s.Avatar,
			NewMessage: decodedStr,
			Name:       s.Name,
		}
		Rooms = append(Rooms, data)
	}
	c.HTML(200, "client_List.html", gin.H{
		"data": Rooms,
	})
	rows.Close()
	sqlDb.Close()
}
